package com.it.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.reggie.common.BaseContext;
import com.it.reggie.exception.CustomException;
import com.it.reggie.dao.*;
import com.it.reggie.entity.*;
import com.it.reggie.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author:cyh
 * @data:2022/12/18 15:22
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, Orders> implements IOrderService {
    @Autowired
    OrderDao orderDao;
    @Autowired
    OrderDetailDao orderDetailDao;
    @Autowired
    UserDao userDao;
    @Autowired
    AddressBookDao addressBookDao;
    @Autowired
    ShoppingCartDao shoppingCartDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sumit(Orders orders) {
        //A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCarts = shoppingCartDao.selectList(wrapper);
        if (shoppingCarts==null || shoppingCarts.size()==0){
            throw new CustomException("购物车为空，不能下单");
        }
        //B. 根据当前登录用户id, 查询用户数据
        User user = userDao.selectById(userId);
        //C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookDao.selectById(orders.getAddressBookId());
        if(addressBook == null){
            throw new CustomException("用户地址信息有误，不能下单");
        }

        // 订单号
        long orderId = IdWorker.getId();
        //JDK中提供的一个原子类 AtomicInteger
        //计算购物车商品的总金额时，为保证我们每一次执行的累加计算是一个原子操作
        //AtomicInteger amount = new AtomicInteger(0);

        BigDecimal amount = new BigDecimal(0);//总价

        //D. 组装订单明细数据, 批量保存订单明细
        //List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            // amount 金额单独设置 数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount.add(orderDetail.getAmount());//累加总价
            //orderDetails.add(orderDetail);
            //向订单明细表插入数据，多条数据
            orderDetailDao.insert(orderDetail);
        }

        //E. 组装订单数据, 批量保存订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        orderDao.insert(orders);
        //F. 删除当前用户的购物车列表数据
        shoppingCartDao.delete(wrapper);
    }
}
